package com.zzw.limit.alg.impl;

import com.google.common.util.concurrent.RateLimiter;
import com.zzw.limit.alg.Alg;
import com.zzw.limit.component.anotation.Limit;
import com.zzw.limit.config.LimitProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component
public class TokenBucketAlg implements Alg{

    @Autowired
    private LimitProperties limitProperties;

    private RateLimiter rateLimiter;

    @PostConstruct
    public void init() {
        this.rateLimiter = RateLimiter.create(limitProperties.getTokenBucketQps());
    }

    @Override
    public Boolean tryAcquire(Limit limit) {
        return rateLimiter.tryAcquire();
    }

}
